use std::u64;

use rbatis::{rbdc::DateTime, Error};
use rbs::Value;

use crate::{
    config::AppContext,
    domain::{reply::Reply, topic::Topic},
};

use super::{search_service, setting_service, topic_service};

pub async fn save(reply: &mut Reply) -> Result<u64, Error> {
    let rb = AppContext::rbatis().acquire_begin().await.unwrap();
    let mut tx = rb.defer_async(|mut tx| async move {
        if !tx.done {
            let _ = tx.rollback().await;
        }
    });
    let setting = setting_service::get().await;
    reply.isn = setting.plsh;
    reply.ptime = Some(DateTime::now());
    let exec_result = Reply::insert(&tx, reply).await?;
    //增加回复数量
    let mut topic = topic_service::select_by_id(reply.cid.unwrap()).await;
    let mut new_topic = Topic::default();
    new_topic.id = reply.cid;
    new_topic.num = Some(topic.num.unwrap() + 1);
    let _ = Topic::update_by_column_skip(&tx, &new_topic, "id", true)
        .await
        .unwrap();
    topic.num=new_topic.num;
    search_service::save_document(&topic).unwrap();
    let _ = tx.commit().await;
    match exec_result.last_insert_id {
        Value::U64(id) => Ok(id),
        _ => Err(Error::E(String::from("error"))),
    }
}

pub async fn delete(reply: Reply) -> Result<u64, Error> {
    let rb = AppContext::rbatis().acquire_begin().await.unwrap();
    let mut tx = rb.defer_async(|mut tx| async move {
        if !tx.done {
            let _ = tx.rollback().await;
        }
    });
    let _ = Reply::delete_by_column(&tx, "id", reply.id).await.unwrap();
    //减少回复数量
    let mut topic = topic_service::select_by_id(reply.cid.unwrap()).await;
    let mut new_topic = Topic::default();
    new_topic.id = reply.cid;
    let mut num = topic.num.unwrap();
    if num > 1 {
        num = num - 1;
    }
    new_topic.num = Some(num);
    let _ = Topic::update_by_column_skip(&tx, &new_topic, "id", true)
        .await
        .unwrap();
    topic.num=new_topic.num;
    search_service::save_document(&topic).unwrap();
    let _ = tx.commit().await;
    Ok(reply.id.unwrap())
}
